<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .big {
            width: 600px;
            height: 600px;
            border: 1px solid #000;
            margin: auto;
            position: relative;
        }
        .big div{
            width: 100px;
            height: 100px;
            background-color: #f00;
            position: absolute;
            cursor: move;
        }
    </style>
</head>
<body>

    <div class="big">
        <div></div>
    </div>
    

    <script>

        // 拖拽
        //   鼠标按下    要找到鼠标的位置
        //   鼠标移动
        //   鼠标抬起


        class Drag {
            constructor(smallBox , bigBox) {
                this.smallBox = document.querySelector(smallBox) ;
                this.bigBox = document.querySelector(bigBox) ;
                this.gapX ,this.gapY ;
                // 鼠标按下
                this.down() ;

                this.maxWidth = this.bigBox.clientWidth - this.smallBox.offsetWidth ;
                this.maxHeight = this.bigBox.clientHeight - this.smallBox.offsetHeight ;
            }
            down() {

                // 鼠标按下
                this.smallBox.onmousedown = e => {
                    // 要找到鼠标的位置
                    this.gapX = e.offsetX ;
                    this.gapY = e.offsetY ;
                    this.move() ;
                    this.up() ;
                }
            }
            move() {
                // 鼠标移动
                document.onmousemove = e => {
                    let x = e.x - this.gapX - this.bigBox.offsetLeft ;
                    let y = e.y - this.gapY - this.bigBox.offsetTop ;
                    if(x < 0) x = 0 ; 
                    if(y < 0) y = 0 ;
                    if(x > this.maxWidth) x = this.maxWidth ;
                    if(y > this.maxHeight) y = this.maxHeight ;
                    this.smallBox.style.cssText = `left:${x}px;top:${y}px`;
                    this.up() ;
                }
            }
            up() {
                // 鼠标抬起
                document.onmouseup = () => {
                    console.log(88);
                    document.onmousemove = null ;
                    document.onmouseup = null;
                }
            }
        }


        new Drag('.big div' , '.big');

    </script>
    
</body>
</html>